package com.linln.modules.system.config;

import com.linln.common.config.SimpleJpaRepositoryImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterRegistry;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

import java.util.Date;

/**
 * @author 小懒虫 <auntvt＠163.com>
 * @date 2021/3/19
 */
@Slf4j
@ComponentScan(basePackages = "com.linln.modules.system")
@EnableJpaRepositories(basePackages = "com.linln.modules.system", repositoryBaseClass = SimpleJpaRepositoryImpl.class)
@EntityScan(basePackages = "com.linln.modules.system")
public class SystemAutoConfig {
    @Autowired
    public void registerConverter(ConverterRegistry converterRegistry) {
        converterRegistry.addConverter(String.class, Date.class, new Converter<String, Date>() {
            private final String[] patterns = {"yyyy-MM-dd HH:mm", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH", "yyyy-MM-dd",
                    "yyyy-MM"};

            @Override
            public Date convert(String str) {
                if (StringUtils.isBlank(str)) {
                    return null;
                }
                try {
                    return DateUtils.parseDate(str.trim(), patterns);
                } catch (Exception e) {
                    log.warn(e.getMessage(), e);
                    return null;
                }
            }
        });
    }
}
